package cn.kongwg.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author kongwg
 * @create 2021-05-02 9:47
 */

class MyDemo{
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    Map<String, Object> map = new HashMap<>();

    public void put(String key,Object value) throws InterruptedException {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t ---开始添加");
            map.put(key, value);
            TimeUnit.MILLISECONDS.sleep(300);
            System.out.println(Thread.currentThread().getName() + "\t ---添加完成");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }


    }
    public void get(String key){
        readWriteLock.readLock().lock();
        try {

            System.out.println(Thread.currentThread().getName() + "\t 开始读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "\t 读取完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }

    }
}

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyDemo myDemo = new MyDemo();
        for (int i = 0; i < 6; i++) {
            final int number = i;
            new Thread(() -> {
                try {
                    myDemo.put(number+"",number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
        for (int i = 0; i < 6; i++) {
            final int number = i;
            new Thread(() -> {
                myDemo.get(number+"");
            }, String.valueOf(i)).start();
        }
    }
}
